<template>
  <div id="bdy">
    <div class="tbody">
      <el-steps :active="active" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>
      <!-- 基本信息 -->
      <el-form ref="form" :model="form" label-width="80px">
        <div class="info" v-if="active == 1">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>

            <el-form-item label="商品描述" prop="name">
            <el-input v-model="form.msg"></el-input>
          </el-form-item>

          <el-form-item label="选择商品分类:" label-width="150px">
            <el-cascader
              v-model="form.commodity_category"
              :options="options"
              :props="{ checkStrictly: true }"
              clearable
              @change="handleCategory"
            >
            </el-cascader>
          </el-form-item>

          <el-form-item label="商品属性" prop="categoryname">
            <el-input
              type="text"
              v-model="form.attribute"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="属性值" prop="categoryname">
            <el-input
              type="text"
              v-model="form.attribute_value"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item label="选择商家:" label-width="150px">
            <el-cascader
              v-model="form.merchant"
              :options="merchantsOptions"
              :props="{ checkStrictly: true }"
              clearable
              @change="handleMerchants"
            >
            </el-cascader>
          </el-form-item>

          <el-form-item label="价格" prop="categoryname">
            <el-input
              type="text"
              v-model="form.price"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="库存" prop="categoryname">
            <el-input
              type="text"
              v-model="form.inventory"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <div v-show="false" id="div1"></div>
        </div>
        <div class="info" v-if="active == 2">
          <div v-show="false" id="div1"></div>
          <el-form-item label="封面图" style="margin-top: 66px">
            <el-upload
              :headers="uploadActionHeaders"
              :action="uploadActionUrl"
              :on-success="handleAvatarSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :url="dialogFormAvatarFullUrl"
              :before-upload="beforeAvatarUpload"
              list-type="picture"
              :multiple="false"
            >
              <el-button type="primary" v-once v-if="!hiddenUploadBtn"
                >点击上传
              </el-button>
            </el-upload>
          </el-form-item>
        </div>
        <div class="info" v-if="active == 3">
          <div id="div1"></div>
          <el-form-item>
            <el-button
              type="primary"
              style="margin-left: 50px"
              @click="onSubmit"
              >确认添加</el-button
            >
          </el-form-item>
        </div>

        <el-button style="margin-top: 12px" @click="pre" v-if="active > 1"
          >上一步</el-button
        >
        <el-button style="margin-top: 12px" @click="next" v-if="active < 3"
          >下一步</el-button
        >
      </el-form>
    </div>
  </div>
</template>

<script>
import E from "wangeditor";
import { getlistCategories } from "../api/categories";
import { getlist } from "../api/merchant";
import { addMerchandise } from "../api/productlist";

export default {
  data() {
    return {
      active: 1,
      hiddenUploadBtn: false,
      dialogFormAvatarFullUrl: "",
      form: {
        name: "",
        commodity_category: "",
        merchant: "",
        attribute: "",
        attribute_value: "",
        price: "",
        inventory: "",
        word: "",
        msg:""
      },
      editor: "",

      options: [],
      sumData: [],

      //装商家信息的
      merchantsOptions: [],

      pager: {
        //每页显示条目个数
        pageSize: 5,
        currentPage: 1,
        totalSize: 0,
      },
    };
  },
  methods: {
    //获取分类
    classify() {
      (this.options = []), console.log(this.sumData);

      this.sumData.map((x) => {
        let currentGrade = {
          id: 0,
          parentId: 0,
          value: "",
          label: "",
          children: [],
        };

        // 判断是不是最高级;
        if (x.parentCategoryId == 0) {
          currentGrade.id = x.id;
          currentGrade.value = x.name;
          currentGrade.label = x.name;

          // Object.assign方法用于对象的合并，
          // 将router添加到{}  并赋给obj对象中
          let obj = Object.assign({}, currentGrade);

          this.options.push(obj);
        }

        // 遍历所有的父级组件
        this.options.map((child) => {
          //如果父级组件的id等于当前组件的父级id
          if (child.id == x.parentCategoryId) {
            let children = {
              id: 0,
              parentId: 0,
              value: "",
              label: "",
              // children: [],
            };

            children.id = x.id;
            children.parentId = x.parentCategoryId;
            children.value = x.name;
            children.label = x.name;

            //将子分类装到父级分类的children中
            let obj = Object.assign({}, children);

            child.children.push(obj);
          }
        });
      });

      console.log(this.options);
    },

    //确定添加
    onSubmit() {
      console.log(this.form);
      console.log("确定添加");

      //添加商品接口
      addMerchandise(this.form)
        .then((res) => {
          console.log(res);
          // location.href="/commoditymanagement/productlist"
          this.$router.push("/commoditymanagement/productlist");
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 文件上传前
    beforeAvatarUpload(file) {
      // console.log(this.hiddenUploadBtn);

      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 图片上传成功后
    handleAvatarSuccess(res, file) {
      console.log(res);
      // console.log(file);

      // 显示使用完整路径
      let fullPath = URL.createObjectURL(file.raw);

      this.dialogFormAvatarFullUrl = fullPath;

      //隐藏上传按钮
      this.hiddenUploadBtn = true;
    },

    //删除文件时
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileLength = 0;

      //显示上传按钮
      this.hiddenUploadBtn = false;
    },

    // 预览文件时
    handlePreview(file) {
      console.log(file);
    },

    //跳入下一步
    next() {
      if (this.active++ > 3) this.active = 1;
    },
    //跳入上一步
    pre() {
      if (this.active-- < 2) this.active = 1;
    },
    //拉取数据
    fetchData() {
      let params = {
        pager: this.pager,
      };

      //获取所有分类
      getlistCategories(params.pager)
        .then((res) => {
          var resful = res.data;

          console.log(resful);
          this.tableData = resful.currentData;
          this.pager = resful.pager;
          this.sumData = resful.data;

          //获取分类
          this.classify();
        })
        .catch((err) => {
          console.log(err);
        });

      // 获取所有商家
      getlist(params.pager)
        .then((res) => {
          var resful = res.data.data;

          (this.merchantsOptions = []),
            resful.map((x) => {
              let currentGrade = {
                id: 0,
                parentId: 0,
                value: "",
                label: "",
                //children: [],
              };
              currentGrade.id = x.id;
              currentGrade.value = x.name;
              currentGrade.label = x.name;

              // Object.assign方法用于对象的合并，
              // 将router添加到{}  并赋给obj对象中
              let obj = Object.assign({}, currentGrade);

              this.merchantsOptions.push(obj);
            });

          console.log(this.merchantsOptions);
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //选择分类时
    handleCategory(value) {
      console.log(value);
      if (value == undefined || value == "") {
        this.form.commodity_category = "";
      } else {
        this.form.commodity_category = value[value.length - 1];
      }

      console.log(this.form.commodity_category);
    },
    //  选择商家时
    handleMerchants(value) {
      if (value == undefined || value == "") {
        this.form.merchant = "";
      } else {
        this.form.merchant = value[value.length - 1];
      }
      console.log(this.form.merchant);
    },
  },
  mounted() {
    const editor = new E(`#div1`);

    // 配置 server 接口地址
    editor.config.uploadImgServer =
      "http://localhost:5000/files/uploadWangEditor";

    editor.config.debug = true; // 开启debug模式

    editor.config.uploadImgMaxSize = 2 * 1024 * 1024; // 2M

    editor.config.height = 500;

    editor.config.uploadImgHooks = {
      // 图片上传并返回结果，但图片插入错误时触发
      fail: function (xhr, editor, result) {
        console.log(result);
      },
      success: function (xhr, editor, result) {
        // 图片上传并返回结果，图片插入成功之后触发
        console.log(result, "success");
      },
    };

    editor.config.uploadImgTimeout = 50000;

    editor.config.onchange = (newHtml) => {
      this.form.word = newHtml;
      console.log(this.form.word);
    };
    // 创建编辑器
    editor.create();

    this.editor = editor;

    this.fetchData();
  },
  computed: {
    uploadActionHeaders() {
      return {
        Authorization: "Bearer " + "token",
      };
    },
    uploadActionUrl() {
      let baseUrl = "http://localhost:5000";
      let url = "/files/uploadfiles";
      return baseUrl + url;
    },
  },
};
</script>


<style scoped>
.tbody {
  width: 80%;
  margin-left: 10%;
  margin-top: 2%;
}
</style>>
